# 导入Flask类库
import base64
import io
import time

from PIL import Image
from flask import Flask, render_template, request, jsonify

from Model.utils.detect_api import Detector
from mapper.sql_connect import SqlConnect

detector = Detector()


# vgg16识别按钮
def detect_img_by_vgg16(image_path):
    pred_str = detector.vgg16_predict(image_path=image_path)
    return pred_str


# resnet50识别按钮
def detect_img_by_resnet50_btn(image_path):
    pred_str = detector.resnet50_predict(image_path=image_path)
    return pred_str


# 创建应用实例,加载静态资源文件
app = Flask(__name__, static_url_path='/static')

# 实例化数据库连接类
sql_connect = SqlConnect()


# 视图函数（路由）
@app.route('/', endpoint='login_register')
def index():
    return render_template('login_register.html')


# 返回功能界面
@app.route('/web/func/', endpoint='func')
def func():
    return render_template('detect_fuc.html')


# 图片预测接口
@app.route('/api/img_api/', methods=['POST'], endpoint='predict')
def predict():
    image = request.get_json()['image']
    # 解码base64字符串
    image_data = base64.b64decode(image)
    filepath = r"./media/image.png"

    # 使用PIL库将二进制数据转换为图像对象
    image = Image.open(io.BytesIO(image_data))

    with open(filepath, "wb") as file:
        image.save(file, "png")
    time.sleep(1)

    # 开始识别垃圾
    result = detector.vgg16_predict("./media/image.png")
    if result != "no detection":
        response_data = {
            'code': 1,
            'message': "success",
            'result': result
        }
        return jsonify(response_data)
    else:
        # 返回错误的响应
        return jsonify("没有检测到鸟类")


# 登录接口
@app.route('/api/login/', methods=['POST'], endpoint='login')
def login():
    username = request.get_json()['username']
    password = request.get_json()['password']
    result = sql_connect.check_login(username, password)
    if result:
        response_data = {
            'code': 1,
            'message': "success",
            'result': "登录成功"
        }
        return jsonify(response_data)
    else:
        # 返回错误的响应
        return jsonify("用户名或密码错误")


# 注册接口
@app.route('/api/register/', methods=['POST'], endpoint='register')
def register():
    username = request.get_json()['username']
    password = request.get_json()['password']
    result = sql_connect.register_user(username, password)
    if result:
        response_data = {
            'code': 1,
            'message': "success",
            'result': "注册成功"
        }
        print(response_data)
        return jsonify(response_data)

    else:
        # 返回错误的响应
        return jsonify("用户名已存在")


# 后台
@app.route('/api/backend/', methods=['GET', 'POST'], endpoint='backend')
def backend_api():
    datas = sql_connect.read_all_users()
    columns = datas.columns.tolist()
    datas = [tuple(x) for _, x in datas.iterrows()]

    return render_template('backend.html', datas=datas, columns=columns)


# 删除用户
@app.route('/api/del_data/', methods=['POST'], endpoint='del_data')
def delete_user():
    username = request.get_json()['username']
    print(username)
    result = sql_connect.delete_user(username)
    if result:
        response_data = {
            'code': 1,
            'message': "success",
            'result': "删除成功"
        }
        return jsonify(response_data)
    else:
        # 返回错误的响应
        return jsonify("删除失败")


# 启动实施（只在当前模块运行）
if __name__ == '__main__':
    app.run()
